<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()" />
    <!-- 搜索栏 -->
    <van-search
      v-model="key"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch(key)">搜索</div>
      </template>
    </van-search>
    <!-- 联想区域 -->
    <van-cell-group v-if="key">
      <van-cell v-for="(item, index) in colorList" :key="index" icon="search">
        <div v-html="item" @click="onSearch(suggestList[index])"></div>
      </van-cell>
    </van-cell-group>
    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item, index) in history"
        :key="index"
        :title="item"
        @click="onSearch(item)"
      />
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI } from '@/api/search'
export default {
  name: 'MySearch',
  data () {
    return {
      key: '',
      suggestList: [],
      history: JSON.parse(localStorage.getItem('history-97')) || []
    }
  },
  methods: {
    onSearch (key) {
      if (key.trim() === '') return this.$toast('请输入搜索内容')
      // 判断这次搜索的内容在不在数组里面
      const index = this.history.indexOf(key)
      if (index !== -1) {
        // 在里面就先删掉
        this.history.splice(index, 1)
      }
      this.history.unshift(key)
      // 先保存历史记录
      localStorage.setItem('history-97', JSON.stringify(this.history))
      // 再跳转
      this.$router.push({
        name: 'result',
        query: {
          key
        }
      })
    },

    // 当我们输入的内容发生改变时调用
    async onInput () {
      if (this.key === '') return
      // 调用接口发请求
      const res = await suggestAPI({
        q: this.key
      })
      if (res.data.options[0]) {
        this.suggestList = res.data.options
      } else {
        this.suggestList = []
      }
    }
  },

  computed: {
    colorList () {
      return this.suggestList.map(v => {
        // 我要找到关键字，把它们用span包起来
        return v.replaceAll(
          this.key,
          `<span style="color:red;">${this.key}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
